package com.hzit.loan.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hzit.loan.pay.config.PayConfig;
import com.hzit.loan.pay.service.INotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付异步回调
 */
@RestController
@RequestMapping("/payNotify")
public class PayNotifyController {

    private Logger logger = LoggerFactory.getLogger(PayNotifyController.class);

    @Autowired
    private PayConfig payConfig;

    @Autowired
    private INotifyService notifyService;

    /**
     * 回调触发条件：
     * 银行或者支付公司的异步回调接口:后端通知
     * @return
     */
    @RequestMapping("/recive")
    public String recive(HttpServletRequest request){

//      1.获取请求参数
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        logger.info("支付宝异步通知返回requestParams参数：{}",requestParams);

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        logger.info("支付宝异步通知返回参数params：{}",params);


//      2.验证签名：确保请求是支付公司发出的
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, payConfig.getAliapyPubKey(), "UTF-8", "RSA2");
            if(!flag){
                logger.info("验证签名失败,flag：{}",flag);
                return "fail";
            }

           return notifyService.doNotify(params);

        } catch (AlipayApiException e) {
            logger.error("AlipayApiException",e);
            return "fail";
        }

    }
}
